﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EmptyWallGallery.Core;
using EmptyWallGallery.Core.Utilities;

namespace EmptyWallGallery.FrontEnd.inside.Editor.Articles
{
    public partial class ArticleUpdate : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            switch (Request.QueryString["MsgID"])
            {
                case "2":
                    lblError.Attributes.Remove("style");
                    lblError.InnerHtml = "Tin bài đã được đăng.";
                    //<a target=""_blank"" href=""" & Configs.HomeUrl & "Preview/Article/?ID=" & Request.QueryString("ID") & """ title=""View Post"">View post</a>"
                    break;
                case "4":
                    lblError.Attributes.Remove("style");
                    lblError.InnerHtml = "Tin bài đã được cập nhật.";

                    if(Request.QueryString["ReUrl"] != null)
                    {
                        lblError.InnerHtml += "<a href='" + Request.QueryString["ReUrl"] + "'>[ Trở lại ]</a>";
                    }
                    break;
                case "6":
                    lblError.Attributes.Remove("style");
                    lblError.InnerHtml = "Tin bài đã được đăng.";
                    //<a target=""_blank"" href=""" & Configs.HomeUrl & "Published/Article/?ID=" & Request.QueryString("ID") & """ title=""View post"">View post</a>"
                    break;
                case "7":
                    lblError.Attributes.Remove("style");
                    lblError.InnerHtml = "Tin bài đã được lưu.";
                    break;
            }

            if (IsPostBack) return;

            if (Request.QueryString["ID"] != null)
            {
                LoadArticle(int.Parse(Request.QueryString["ID"]));

                Page.Title = "Thay đổi tin bài - " + Configs.WebTitle;
            }
            else
            {
                Response.Redirect("default.aspx");
            }
        }

        public void LoadArticle(int id)
        {
            var articleItem = Core.BLL.Articles.Instance.GetByEdit(id);

            if (articleItem == null) { Response.Redirect("default.aspx"); }

            if (articleItem != null)
            {
                txtBody.Value = Server.HtmlDecode(articleItem.Body);
                txtTitle.Text = Server.HtmlDecode(articleItem.Title.Trim());
                txtTitleNone.Value = articleItem.TitleNone;
                txtDesc.Text = Server.HtmlDecode(Common.Instance.FormatBrToMultiline(articleItem.Abstract));
                txtArticlePath.Value = articleItem.ArticlePath;
                txtImagePath.Value = articleItem.ImagePath;
                txtCreateDate.Value = Convert.ToString(articleItem.CreatedDate);
                //cboPostVisible.Checked = articleItem.PostVisible == 0;
                ArticlePublishContent.InnerHtml = WriteScheduleDate(Convert.ToDateTime(articleItem.ReleaseDate));
            }

            catdetail.InnerHtml = Core.BLL.Categories.Instance.WriteCategoryInside(3, 1, Core.BLL.Articles.Instance.GetAllCat(1, id));

            if (articleItem != null && string.IsNullOrEmpty(articleItem.ImagePath))
            {
                imgPreView.ImageUrl = "/images/no-image.jpg";
            }
            else
            {
                if (articleItem != null) imgPreView.ImageUrl = "/Uploads/" + articleItem.ImagePath;
                //imgPreView.Width = Unit.Parse("130");
                //imgPreView.Height = Unit.Parse("130");
            }
        }

        protected void BtnUpdateClick(object sender, EventArgs e)
        {
            var strCatTemp = "";
            var articleId = int.Parse(Request.QueryString["ID"]);
            string imagePath;

            if (txtTitle.Text == "")
            {
                txtTitle.Text = "No Title";
            }
            else if (txtTitle.Text.Length > 550)
            {
                txtTitle.Text = Server.HtmlEncode(txtTitle.Text.Trim().Substring(0, 500));
            }

            var strTitle = Common.Instance.NoHtml(Server.HtmlEncode(txtTitle.Text.Trim()));
            var strBody = txtBody.Value;
            var strAbstract = Server.HtmlEncode(Common.Instance.FormatMultiline(txtDesc.Text.Trim()));
            var releaseDate = Convert.ToDateTime(Request.Form["txtReleaseDate"]);

            if (fileUpload.HasFile)
            {
                var randomStr = new RandomStrings();
                var strFileName = randomStr.GenerateRandomString(DateTime.Now) + ".jpg";
                var strFolder = string.Format("{0}{1}\\{2}\\{3}\\{4}\\", Configs.UserFolder,
                                              HttpContext.Current.User.Identity.Name, DateTime.Now.Year,
                                              Common.Instance.Right("0" + DateTime.Now.Month, 2),
                                              Common.Instance.Right("0" + DateTime.Now.Day, 2));
                if (!Directory.Exists(strFolder))
                {
                    Directory.CreateDirectory(strFolder);
                }

                var objImage = new ImageUtil(fileUpload.PostedFile.InputStream, 1024, 1024, "UploadService", "admin", strFileName, 100);
                objImage.PublicUpload(300, 0, strFileName, 100, "", strFolder);
                objImage.PublicUpload(202, 0, strFileName, 100, "", strFolder);
                objImage.PublicUpload(145, 0, strFileName, 100, "", strFolder);
                objImage.PublicUpload(100, 0, strFileName, 100, "", strFolder);
                objImage.PublicUpload(42, 0, strFileName, 100, "", strFolder);

                imagePath = strFolder.Replace(Configs.UserFolder, "").Replace("\\", "/") + "100x0__" + strFileName;
            }
            else
            {
                imagePath = txtImagePath.Value;
            }

            //Update Article
            var articleItem = Core.BLL.Articles.Instance.Update(strTitle, strAbstract, true, false, imagePath, articleId,
                                                                releaseDate);

            //Remove Old Article Cat
            Core.BLL.Articles.Instance.RemoveTempArticleCat(articleItem.ArticlesId);

            //Create Category
            if (Request.Form.Get("cboCategory") == null)
            {
                Core.BLL.Articles.Instance.SetTempArticleCat(1, 1, articleItem.ArticlesId);
            }
            else
            {
                foreach (var strCatId in Regex.Split(Request.Form.Get("cboCategory"), ","))
                {
                    strCatTemp = strCatId;

                    var str = strCatTemp.Split(new[] { '|' });
                    Core.BLL.Articles.Instance.SetTempArticleCat(1, int.Parse(str[0]), articleItem.ArticlesId);
                }
            }

            Core.BLL.Articles.Instance.WriteXmlbyId(articleItem, strBody, strCatTemp);

            var reUrl = "";
            if (Request.QueryString["ReUrl"] != null)
            {
                reUrl = Server.UrlEncode(Request.QueryString["ReUrl"]);
            }

            Response.Redirect("ArticleUpdate.aspx?ID=" + articleItem.ArticlesId + "&MsgID=4&ReUrl=" + reUrl);
        }

        public string WriteScheduleDate(DateTime releaseDate)
        {
            var strOut = new StringBuilder();
            strOut.Append(
                "<br /><select name=\"mmmm\" id=\"mmmm\"><option value=\"1\">Jan</option><option value=\"2\">Feb</option><option value=\"3\">Mar</option><option value=\"4\">Apr</option><option value=\"5\">May</option><option value=\"6\">Jun</option><option value=\"7\">Jul</option><option value=\"8\">Aug</option><option value=\"9\">Sep</option><option value=\"10\">Oct</option><option value=\"11\">Nov</option><option value=\"12\">Dec</option></select> ");
            strOut.Append("<input type=\"text\" style=\"width:auto;\" id=\"dd\" name=\"dd\" value=\"").Append(
                releaseDate.Day).Append("\" size=\"2\" maxlength=\"2\" autocomplete=\"off\" />");
            strOut.Append(", <input type=\"text\" style=\"width:auto;\" id=\"yy\" name=\"yy\" value=\"").Append(
                releaseDate.Year).Append(
                    "\" size=\"4\" maxlength=\"4\" tabindex=\"4\" autocomplete=\"off\" /> @ <input style=\"width:auto;\" type=\"text\" id=\"hh\" name=\"hh\" value=\"")
                .Append(releaseDate.Hour).Append(
                    "\" size=\"2\" maxlength=\"2\" tabindex=\"4\" autocomplete=\"off\" /> : <input style=\"width:auto;\" type=\"text\" id=\"mn\" name=\"mn\" value=\"")
                .Append(releaseDate.Minute).Append(
                    "\" size=\"2\" maxlength=\"2\" tabindex=\"4\" autocomplete=\"off\" /><input type=\"hidden\" id=\"ss\" name=\"ss\" value=\"")
                .Append(releaseDate.Second).Append("\" />");
            strOut.Append(
                "<input type=\"button\" value=\"OK\" class=\"button\" onclick=\"javascript:Util.PublishConfirmAction();\" /> ");
            strOut.Append(
                "<a onclick=\"javascript:Util.CancelArticlePublish();\" title=\"Cancel\" href=\"javascript:void(0);\">Cancel</a><input type=\"hidden\" id=\"txtReleaseDate\" value=\"")
                .Append(releaseDate).Append("\" name=\"txtReleaseDate\" />");
            strOut.Append("<script type=\"text/javascript\" language=\"javascript\">gmobj(\"mmmm\").value = ").Append(
                releaseDate.Month).Append(";</script>");
            return strOut.ToString();
        }
    }
}